﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TmU220PrintHelperV2d0.Entity;
using System.Collections.Concurrent;
using TmU220PrintHelperV2d0.Service;
using System.Threading;
using System.Net.Sockets;
using ZhangLogSysV1d0;

namespace TmU220PrintHelperV2d0.ControlUi
{
    public partial class VirtualPrinterMonitorV2d0 : UserControl
    {
        public VirtualPrinterMonitorV2d0()
        {
            InitializeComponent();
            UpdateCountOfStatus = 0;
            RmsPrinter = new rms_printer();
            RealPrinterMonitor = new TmU220PrinterMonitorV2d0();
            InitSignList();
            InitPrinterInfo();
            //PrintTaskQueue = new ConcurrentQueue<PrintTaskV2d0>();
            TaskCountOfReceived = 0;
            TaskCountOfPrintComplete = 0;
            DeviceType = "TM-U220";
        }
        public VirtualPrinterMonitorV2d0(rms_printer rmsPrinter,TmU220PrinterMonitorV2d0 printerMonitor)
        {
            InitializeComponent();
            //PrintTaskQueue = new ConcurrentQueue<PrintTaskV2d0>();
            RmsPrinter = rmsPrinter;
            UpdateCountOfStatus = 0;
            InitPrinterInfo();
            InitSignList();
            RealPrinterMonitor = printerMonitor;
            RealPrinterMonitor.PrinterStatusEvent += ProcPrinterStatusEvent;
            RealPrinterMonitor.PrintCompleteEvent += ProcPrintCompleteEvent;
            RealPrinterMonitor.PrintErrorEvent += ProcPrintErrorEvent;

        }
        public void Init(rms_printer rmsPrinter, TmU220PrinterMonitorV2d0 printerMonitor)
        {
            RmsPrinter = rmsPrinter;
            //PrintTaskQueue = new ConcurrentQueue<PrintTaskV2d0>();
            UpdateCountOfStatus = 0;
            InitPrinterInfo();
            InitSignList();
            RealPrinterMonitor = printerMonitor;
            RealPrinterMonitor.PrinterStatusEvent -= ProcPrinterStatusEvent;
            RealPrinterMonitor.PrintCompleteEvent -= ProcPrintCompleteEvent;
            RealPrinterMonitor.PrintErrorEvent -= ProcPrintErrorEvent;
            RealPrinterMonitor.PrinterStatusEvent += ProcPrinterStatusEvent;
            RealPrinterMonitor.PrintCompleteEvent += ProcPrintCompleteEvent;
            RealPrinterMonitor.PrintErrorEvent += ProcPrintErrorEvent;
        }
        /// <summary>
        /// 添加任务到队列
        /// </summary>
        /// <param name="printTask"></param>
        public bool AddPrintTaskToQueue(PrintTaskV2d0 printTask)
        {
            bool result = false;
            try
            {
                TaskCountOfReceived++;
                RefreshDisplayOfTaskCountInfo();
                //将任务添加到虚拟打印机对应的物理打印机队列中
                RealPrinterMonitor.AddPrintTaskToQueue(printTask);
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return result;
        }
        public void RefreshDisplayOfTaskCountInfo()
        {
            toolStripStatusLabelQueueCount.Text = string.Format("{0}/{1}", TaskCountOfPrintComplete, TaskCountOfReceived);
        }
        /// <summary>
        /// 卸载队列中的所有任务
        /// </summary>
        /// <returns></returns>
        public List<PrintTaskV2d0> UnloadPrintTaskFromQueue()
        {
            List<PrintTaskV2d0> resultList = new List<PrintTaskV2d0>();
            try
            {
                if (!IsConnected | !IsPrinterReady)
                {

                    resultList = RealPrinterMonitor.UnloadPrintTaskFromQueue();
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return resultList;
        }

        /// <summary>
        /// 处理打印机状态事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="printerStatus"></param>
        public void ProcPrinterStatusEvent(object sender, PrinterStatusV2d0 printerStatus)
        {
            try
            {
                UpdateStatusBar(printerStatus);
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }

        }
        /// <summary>
        /// 处理打印完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="printTask"></param>
        public void ProcPrintCompleteEvent(object sender, PrintTaskV2d0 printTask)
        {
            //"打印完成");
            // 
            if (printTask.DataOfPrintTask.printer == PrinterName)
            {
                TaskCountOfPrintComplete++;
            }

            RefreshDisplayOfTaskCountInfo();
            if (PrintCompleteEvent != null) PrintCompleteEvent(this, printTask);
            try
            {
                // UpdateStatusBarCountOfQueue(DataQueue.Count);
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 处理打印错误事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="printTask"></param>
        public void ProcPrintErrorEvent(object sender, PrintTaskV2d0 printTask)
        {
            if (PrintErrorEvent != null) PrintErrorEvent(this, printTask);

        }

        private void UpdateStatusBarCountOfQueue(int countOfQueue)
        {
            this.toolStripStatusLabelQueueCount.Text = countOfQueue.ToString("D3");
        }

        /// <summary>
        /// 更新状态栏 ip_port,is_online,is_ready
        /// </summary>
        private void UpdateStatusBar(PrinterStatusV2d0 printerStatus)
        {
            UpdateCountOfStatus++;
            IsConnected = printerStatus.IsConnected;
            IsPrinterReady = printerStatus.IsPrinterReady;
            this.Invoke(new Action(() =>
            {
                if (printerStatus.IsConnected)
                {
                    toolStripStatusLabelOnline.Text = "联机";
                }
                else
                {
                    toolStripStatusLabelOnline.Text = "未联机";
                }

                if (printerStatus.IsPrinterReady)
                {
                    toolStripStatusLabelReady.Text = "正常";
                }
                else
                {
                    toolStripStatusLabelReady.Text = "故障";
                }

                if (printerStatus.IsJzgNormal)
                {
                    toolStripStatusLabelJzgStatus.Text = "卷纸盖正常";
                }
                else
                {
                    toolStripStatusLabelJzgStatus.Text = "卷纸盖打开";
                }
                if (printerStatus.IsConnected && printerStatus.IsPrinterReady && printerStatus.IsJzgNormal)
                {
                    this.statusStrip1.BackColor = Color.FromName("Control");
                    this.statusStrip1.BackColor = Color.FromArgb(0xBB, 0xFF, 0x99);
                }
                else
                {
                    this.statusStrip1.BackColor = Color.FromArgb(0xFF, 0x80, 0x80);
                }
                // 刷新进度指示
                RefreshSign();
            }));
        }

        private void InitSignList()
        {
            SignList = new List<string>();
            SignList.Add(@"--");
            SignList.Add(@"\");
            SignList.Add(@"|");
            SignList.Add(@"/");
        }
        private void InitPrinterInfo()
        {
            TaskCountOfReceived = 0;
            TaskCountOfPrintComplete = 0;
            PrinterName = RmsPrinter.printername;
            BackupPrinterName = RmsPrinter.backup_printer;
            PrinterIp = RmsPrinter.ip;
            PrinterPort = RmsPrinter.port.HasValue ? RmsPrinter.port.Value : 9100;
            FirstInfoLine = string.Format("{0}({1})",RmsPrinter.name1, RmsPrinter.printername);
            SecondInfoLine = string.Format("后备:{0}", RmsPrinter.backup_printer);
            DeviceType = RmsPrinter.device_type;
            label_FirstInfoLine.Text = FirstInfoLine;
            label_SecondInfoLine.Text = SecondInfoLine;
            toolStripStatusLabelIpPort.Text = RmsPrinter.ip;
            toolStripStatusLabelQueueCount.Text = string.Format("{0}/{1}", TaskCountOfPrintComplete, TaskCountOfReceived);

        }
        private void RefreshSign()
        {
            this.toolStripStatusLabelPulseCheck.Text = SignList[UpdateCountOfStatus % 4];
        }
        /// <summary>
        /// 停止运行
        /// </summary>
        public void StopRunning()
        {
            RealPrinterMonitor.PrinterStatusEvent -= ProcPrinterStatusEvent;
            RealPrinterMonitor.PrintCompleteEvent -= ProcPrintCompleteEvent;
            RealPrinterMonitor.PrintErrorEvent -= ProcPrintErrorEvent;
        }

        #region 基本属性
        public rms_printer RmsPrinter { get; set; }
        /// <summary>
        /// 打印机名称
        /// </summary>
        public string PrinterName { get; set; }
        public string PrinterIp { get; set; }
        public int PrinterPort { get; set; }
        public string BackupPrinterName { get; set; }
        public string FirstInfoLine { get; set; }
        public string SecondInfoLine { get; set; }
        public string DeviceType { get; set; }
        /// <summary>
        /// 打印机状态刷新次数，每接收到一个打印机状态时间，该值增加1
        /// </summary>
        public int UpdateCountOfStatus { get; set; }
        /// <summary>
        ///  接收到的任务数量
        /// </summary>
        public int TaskCountOfReceived { get; set; }
        /// <summary>
        /// 已打印完成的任务数量
        /// </summary>
        public int TaskCountOfPrintComplete { get; set; }
        /// <summary>
        /// 用于指示刷新状态的符号列表
        /// </summary>
        public List<string> SignList { get; set; }
        //打印任务的数据队列
        // private ConcurrentQueue<PrintTaskV2d0> PrintTaskQueue;
        #endregion
        #region 打印机状态
        private bool _IsConnected;
        /// <summary>
        /// 是否已与打印机连接
        /// </summary>
        public bool IsConnected
        {
            get
            {
                lock (LockIsConnected)
                {
                    return _IsConnected;
                }
            }
            set
            {
                lock (LockIsConnected)
                {
                    _IsConnected = value;
                }
            }
        }
        private object LockIsConnected = new object();

        private bool _IsJzgNormal;
        /// <summary>
        /// 卷纸盖是否正常（卷纸盖关闭未正常，打开为异常）
        /// </summary>
        private bool IsJzgNormal
        {
            get
            {
                lock (LockIsJzgNormal)
                {
                    return _IsJzgNormal;
                }
            }
            set
            {
                lock (LockIsJzgNormal)
                {
                    _IsJzgNormal = value;
                }
            }
        }
        private object LockIsJzgNormal = new object();

        private bool _IsPrinterReady;
        /// <summary>
        /// 打印机是否就绪
        /// </summary>
        public bool IsPrinterReady
        {
            get
            {
                lock (LockIsPrinterReady)
                {
                    return _IsPrinterReady;
                }
            }
            set
            {
                lock (LockIsPrinterReady)
                {
                    _IsPrinterReady = value;
                }
            }
        }
        private object LockIsPrinterReady = new object();
        private bool _IsPaperExhausted;

        private TmU220PrinterMonitorV2d0 RealPrinterMonitor;

        #endregion
        #region 对外发布的事件
        /// <summary>
        /// 打印机状态改变事件
        /// </summary>
        public event EventHandler<PrinterStatusV2d0> PrinterStatusEvent = null;
        /// <summary>
        /// 打印任务完成事件
        /// </summary>
        public event EventHandler<PrintTaskV2d0> PrintCompleteEvent = null;
        /// <summary>
        /// 打印任务错误事件
        /// </summary>
        public event EventHandler<PrintTaskV2d0> PrintErrorEvent = null;
        #endregion
    }
}